package org.yray.sip.factory;


import io.netty.util.Timeout;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.yray.sip.constant.SessionStatusEnum;
import org.yray.sip.server.SipSession;

import java.util.List;
import java.util.Optional;

@Component
public class SipSessionFactory {







    public boolean isToMan(SipSession sipSession)
    {
        return  sipSession.getStatus().get()== SessionStatusEnum.TO_MAN_ING||
                sipSession.getStatus().get()== SessionStatusEnum.TO_MAN_RING||
                sipSession.getStatus().get()==SessionStatusEnum.TO_MAN_SUCC;
    }

    public boolean isClose(SipSession sipSession)
    {
        return sipSession.getStatus().get()==SessionStatusEnum.CLOSE;
    }
    public void doToManExt(SipSession sipSession,String ext)
    {
        sipSession.setToManExt(ext.split(","));
        sipSession.setToManIndex(0);
        sipSession.setTo(sipSession.getToManExt()[sipSession.getToManIndex()]);
        sipSession.setStopAsr(true);
        sipSession.getStatus().set(SessionStatusEnum.TO_MAN_ING);
    }

    public boolean canToMan(SipSession sipSession)
    {
        sipSession.setToManIndex(sipSession.getToManIndex()+1);
        if(sipSession.getToManIndex()>=sipSession.getToManExt().length) {
            return false;
        }
        sipSession.setTo(sipSession.getToManExt()[sipSession.getToManIndex()]);
        return true;
    }

    public  void resolvRtp(SipSession sipSession,List<String> sdpList)
    {
        if(!CollectionUtils.isEmpty(sdpList)) {
            for (String sdpStr : sdpList) {
                //m=audio 27530 RTP/AVP 8 101
                if (sdpStr.indexOf("m=audio") > -1) {
                    sipSession.setSideRtpPort(Integer.valueOf(sdpStr.split(" ")[1])) ;
                }
                //a=rtcp:27531 IN IP4 172.168.200.78
                else if (sdpStr.indexOf("a=rtcp") > -1) {
                    String[] strs = sdpStr.split(" ");
                    sipSession.setSideRtcpPort(Integer.valueOf(strs[0].split(":")[1]));
                    sipSession.setSideRtcpIp(strs[3]);

                }
            }
        }
    }

    public void addOutTimeTask(SipSession sipSession, Timeout timeout)
    {
        Timeout tempTimeout=sipSession.getTimeout();
        if(tempTimeout==null)
        {
            sipSession.setTimeout(timeout);
            return;
        }
        if(!tempTimeout.isCancelled()) {
            tempTimeout.cancel();
        }
        sipSession.setTimeout(timeout);
    }

    public void removeOutTimeTask(SipSession sipSession)
    {
        Timeout tempTimeout=sipSession.getTimeout();
        if(tempTimeout==null)
        {
            return;
        }
        if(!tempTimeout.isCancelled()) {
            tempTimeout.cancel();
        }

    }
}
